package com.yswee.framework.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import com.yswee.framework.Application;

import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

public class DeviceUtils {

	@SuppressWarnings("deprecation")
	public static String getIMEI() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
			String imei = tm.getDeviceId();
			if(StringUtils.isEmpty(imei)) {
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
					imei = tm.getDeviceId(0);
				}
			}
			return imei;
		} catch (Exception e) {
			return "";
		}
	}
	
	public static String getPhoneNumber() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
		    String v = tm.getLine1Number();
			if(v == null) {
				v = "";
			}
			return v;
		} catch (Exception e) {
			return "";
		}
	}
	
	public static String getNetworkCountryIso() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
			String v = tm.getNetworkCountryIso();
			if(v == null) {
				v = "";
			}
			return v;
		} catch (Exception e) {
			return "";
		}
	}
	
	public static String getNetworkOperator() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
			String v = tm.getNetworkOperator();
			if(v == null) {
				v = "";
			}
			return v;
		} catch (Exception e) {
			return "";
		}
	}
	
	public static String getNetworkOperatorName() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
			String v = tm.getNetworkOperatorName();
			if(v == null) {
				v = "";
			}
			return v;
		} catch (Exception e) {
			return "";
		}
	}
	
	/**
	 * 
	 * @return
	 * @see #NETWORK_TYPE_UNKNOWN
     * @see #NETWORK_TYPE_GPRS
     * @see #NETWORK_TYPE_EDGE
     * @see #NETWORK_TYPE_UMTS
     * @see #NETWORK_TYPE_HSDPA
     * @see #NETWORK_TYPE_HSUPA
     * @see #NETWORK_TYPE_HSPA
     * @see #NETWORK_TYPE_CDMA
     * @see #NETWORK_TYPE_EVDO_0
     * @see #NETWORK_TYPE_EVDO_A
     * @see #NETWORK_TYPE_EVDO_B
     * @see #NETWORK_TYPE_1xRTT
     * @see #NETWORK_TYPE_IDEN
     * @see #NETWORK_TYPE_LTE
     * @see #NETWORK_TYPE_EHRPD
     * @see #NETWORK_TYPE_HSPAP
     */
	public static int getNetworkType() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
		    return tm.getNetworkType();
		} catch (Exception e) {
			return TelephonyManager.NETWORK_TYPE_UNKNOWN;
		}
	}
	
	/**
	 * 
	 * @return
     * @see #PHONE_TYPE_NONE
     * @see #PHONE_TYPE_GSM
     * @see #PHONE_TYPE_CDMA
     * @see #PHONE_TYPE_SIP
	 */
	public static int getPhoneType() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
		    return tm.getPhoneType();
		} catch (Exception e) {
			return TelephonyManager.PHONE_TYPE_NONE;
		}
	}

	public static String getSimCountryIso() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
			String v = tm.getSimCountryIso();
			if(v == null) {
				v = "";
			}
			return v;
		} catch (Exception e) {
			return "";
		}
	}

	public static String getSimOperator() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
			String v = tm.getSimOperator();
			if(v == null) {
				v = "";
			}
			return v;
		} catch (Exception e) {
			return "";
		}
	}

	public static String getSimOperatorName() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
			String v = tm.getSimOperatorName();
			if(v == null) {
				v = "";
			}
			return v;
		} catch (Exception e) {
			return "";
		}
	}

	public static String getSimSerialNumber() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
			String v = tm.getSimSerialNumber();
			if(v == null) {
				v = "";
			}
			return v;
		} catch (Exception e) {
			return "";
		}
	}

	/*
	 * @return
     * @see #SIM_STATE_UNKNOWN
     * @see #SIM_STATE_ABSENT
     * @see #SIM_STATE_PIN_REQUIRED
     * @see #SIM_STATE_PUK_REQUIRED
     * @see #SIM_STATE_NETWORK_LOCKED
     * @see #SIM_STATE_READY
	 */
	public static int getSimState() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
		    return tm.getSimState();
		} catch (Exception e) {
			return TelephonyManager.SIM_STATE_UNKNOWN;
		}
	}

	/**
	 * IMSI
	 * @return
	 */
	public static String getSubscriberId() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
			String v = tm.getSubscriberId();
			if(v == null) {
				v = "";
			}
			return v;
		} catch (Exception e) {
			return "";
		}
	}
	
	public static String getVoiceMailNumber() {
		try {
			TelephonyManager tm = (TelephonyManager) Application.get().
					getSystemService(Context.TELEPHONY_SERVICE);     
			String v = tm.getVoiceMailNumber();
			if(v == null) {
				v = "";
			}
			return v;
		} catch (Exception e) {
			return "";
		}
	}
	
	/**
	 * 获取mac地址
	 * @return
	 */
	public static String getMacAddress() {
		String macaddress = null;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            macaddress = getLocalMacAddressFromWifiInfo();
            return macaddress;
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            macaddress = getLocalMacAddressFromCat();
            return macaddress;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        	macaddress = getLocalMacAddressFromIpAddress();
            if (!TextUtils.isEmpty(macaddress)) {
                return macaddress;
            }
            macaddress = getMachineHardwareAddress();
            if (!TextUtils.isEmpty(macaddress)) {
                return macaddress;
            }
            macaddress = getLocalMacAddressFromBusybox();
            if (!TextUtils.isEmpty(macaddress)) {
                return macaddress;
            }
        }
        return "02:00:00:00:00:00";
	}

	/**
     * 根据wifi信息获取本地mac
     * @param context
     * @return
     */
    private static String getLocalMacAddressFromWifiInfo() {
    	Context context = Application.get();
    	if (isAccessWifiStateAuthorized(context)) {
            WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = null;
            try {
                wifiInfo = wifiMgr.getConnectionInfo();
                return wifiInfo.getMacAddress();
            } catch (Exception e) {
            	e.printStackTrace();
            }
        }
        return "";
    }

    private static boolean isAccessWifiStateAuthorized(Context context) {
        if (PackageManager.PERMISSION_GRANTED == context
                .checkCallingOrSelfPermission("android.permission.ACCESS_WIFI_STATE")) {
            return true;
        } else
            return false;
    }
 
    private static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }
 
    private static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }

	/**
     * android 6.0及以上、7.0以下 获取mac地址
     * @param context
     * @return
     */
    private static String getLocalMacAddressFromCat() {
        String str = "";
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (macSerial == null || "".equals(macSerial)) {
            try {
                return loadFileAsString("/sys/class/net/eth0/address")
                        .toUpperCase().substring(0, 17);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("----->" + "NetInfoManager",
                        "getMacAddress:" + e.toString());
            }
 
        }
        return macSerial;
    }

    /**
     * 根据IP地址获取MAC地址
     *
     * @return
     */
    public static String getLocalMacAddressFromIpAddress() {
        String strMacAddr = null;
        try {
            // 获得IpD地址
            InetAddress ip = getLocalInetAddress();
            byte[] b = NetworkInterface.getByInetAddress(ip)
                    .getHardwareAddress();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < b.length; i++) {
                if (i != 0) {
                    buffer.append(':');
                }
                String str = Integer.toHexString(b[i] & 0xFF);
                buffer.append(str.length() == 1 ? 0 + str : str);
            }
            strMacAddr = buffer.toString().toUpperCase();
        } catch (Exception e) {
        }
        return strMacAddr;
    }

	public static String getIpAddress() {
		InetAddress ia = getLocalInetAddress();
		if (ia != null) {
			return ia.getHostAddress();
		}
		return "";
	}
    
    public static InetAddress getLocalInetAddress() {
    	InetAddress ip = null;
        try {
            // 列举
            Enumeration<NetworkInterface> en_netInterface = NetworkInterface
                    .getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {// 是否还有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface
                        .nextElement();// 得到下一个元素
                Enumeration<InetAddress> en_ip = ni.getInetAddresses();// 得到一个ip地址的列举
                while (en_ip.hasMoreElements()) {
                    ip = en_ip.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
                        break;
                    } else {
                        ip = null;
                    }
                }
 
                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ip;
    }

    public static String getMachineHardwareAddress() {
        Enumeration<NetworkInterface> interfaces = null;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        String hardWareAddress = null;
        NetworkInterface iF = null;
        if (interfaces == null) {
            return null;
        }
        while (interfaces.hasMoreElements()) {
            iF = interfaces.nextElement();
            try {
                hardWareAddress = bytesToString(iF.getHardwareAddress());
                if (hardWareAddress != null)
                    break;
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
        return hardWareAddress;
    }
 
    private static String bytesToString(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        StringBuilder buf = new StringBuilder();
        for (byte b : bytes) {
            buf.append(String.format("%02X:", b));
        }
        if (buf.length() > 0) {
            buf.deleteCharAt(buf.length() - 1);
        }
        return buf.toString();
    }
    
    /**
     * 根据busybox获取本地Mac
     *
     * @return
     */
    private static String getLocalMacAddressFromBusybox() {
        String result = "";
        String Mac = "";
        result = callCmd("busybox ifconfig", "HWaddr");
        // 如果返回的result == null，则说明网络不可取
        if (result == null) {
            return "网络异常";
        }
        // 对该行数据进行解析
        // 例如：eth0 Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67
        if (result.length() > 0 && result.contains("HWaddr") == true) {
            Mac = result.substring(result.indexOf("HWaddr") + 6,
                    result.length() - 1);
            result = Mac;
        }
        return result;
    }
 
    private static String callCmd(String cmd, String filter) {
        String result = "";
        String line = "";
        try {
            Process proc = Runtime.getRuntime().exec(cmd);
            InputStreamReader is = new InputStreamReader(proc.getInputStream());
            BufferedReader br = new BufferedReader(is);
 
            while ((line = br.readLine()) != null
                    && line.contains(filter) == false) {
                result += line;
            }
 
            result = line;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
	
	/**
	 * 获取设备唯一编码 md5(imei+mac)
	 * @return
	 */
	public static String getUniqueId() {
		try {
			String imei = getIMEI();
			String macAddr = getMacAddress();
			String unique = imei + macAddr;
			return StringUtils.MD5(unique);
		} catch (Exception e) {
			return "";
		}
	}
}